<template>
  <div class="tell-manage-container">
    <div class="search-area">
      <div class="search-item">
        <span>姓名：</span>
        <el-input v-model="patientName" placeholder="请输入患者姓名" class="search-input"></el-input>
      </div>
      <el-button type="primary" @click="searchData">搜索</el-button>
      <el-button type="success" @click="addNew">添加医嘱</el-button>
    </div>

    <div class="table-container">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="bedCode" label="床位" width="100" align="center"></el-table-column>
        <el-table-column prop="patientName" label="病人" width="120" align="center"></el-table-column>
        <el-table-column prop="doctorContent" label="医嘱内容" min-width="200" align="center"></el-table-column>
        <el-table-column label="医嘱开始日期" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.doctorSTime) }}
          </template>
        </el-table-column>
        <el-table-column label="医嘱结束日期" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.doctorETime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <span :class="isEffective(scope.row.doctorSTime, scope.row.doctorETime) ? 'status-published' : 'status-unpublished'">
              {{ isEffective(scope.row.doctorSTime, scope.row.doctorETime) ? '生效中' : '失效' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
            <el-link type="danger" class="ml-10" @click="handleDelete(scope.row)">删除</el-link>
            <el-link 
              v-if="!isEffective(scope.row.doctorSTime, scope.row.doctorETime) && scope.row.isPublisher === 0" 
              type="success" 
              class="ml-10"
              @click="handlePublish(scope.row)"
            >发布</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑医嘱对话框 -->
    <el-dialog
      :title="dialogStatus === 'add' ? '添加医嘱' : '编辑医嘱'"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      class="doctor-dialog"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="doctor-form"
      >
        <el-form-item label="床位：" prop="bedCode">
          <el-select v-model="form.bedCode" placeholder="请选择床位" style="width: 100%">
            <el-option
              v-for="item in bedOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="患者：" prop="patientCode">
          <el-select v-model="form.patientCode" placeholder="请选择患者" style="width: 100%" @change="handlePatientChange">
            <el-option
              v-for="item in patientOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="开始日期：" prop="doctorSTime">
          <el-date-picker
            v-model="form.doctorSTime"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束日期：" prop="doctorETime">
          <el-date-picker
            v-model="form.doctorETime"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="医嘱内容：" prop="doctorContent">
          <el-input
            v-model="form.doctorContent"
            type="textarea"
            :rows="4"
            placeholder="请输入医嘱内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" plain>取 消</el-button>
          <el-button type="primary" @click="submitForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/api/http'
import store from '@/store/index'
import * as signalR from '@microsoft/signalr'

// 全局变量，确保connection不会每次都创建新的
let connection = null;

// 判断医嘱是否生效的方法
const isEffective = (startDate, endDate) => {
  const now = new Date()
  const start = new Date(startDate)
  const end = new Date(endDate)
  
  // 如果当前日期在开始日期和结束日期之间（含边界），则生效中
  return now >= start && now <= end
}

// 初始化SignalR连接
const initSignalRConnection = () => {
  if (!connection) {
    connection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:9991/sendClub') 
      .withAutomaticReconnect()
      .build();
      
    // 启动连接
    connection.start()
      .then(() => {
        console.log('SignalR连接成功建立');
      })
      .catch(err => {
        console.error('SignalR连接失败:', err);
      });
    
    // 监听消息
    connection.on('GetTell', (message) => {
      console.log('收到SignalR消息:', message);
    });
  }
  return connection;
}

// 发送SignalR消息
const sendSignalRMessage = async () => {
  try {
    const conn = initSignalRConnection();
    // 确保连接已经建立
    if (conn.state === signalR.HubConnectionState.Connected) {
      // 调用后端的SendMessage方法，与后端Hub中的方法名一致
      await conn.invoke('SendMessage');
      console.log('SignalR消息发送成功');
    } else {
      console.warn('SignalR连接未建立，尝试重新连接');
      await conn.start();
      await conn.invoke('SendMessage');
    }
  } catch (error) {
    console.error('发送SignalR消息失败:', error);
  }
}

// 定义查询参数
const patientName = ref('')
const tableData = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogStatus = ref('add') // 'add' 或 'edit'
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  bedCode: '',
  patientCode: '',
  patientName: '',
  doctorSTime: '',
  doctorETime: '',
  doctorContent: '',
  doctorCode: '' // 初始为空，稍后会设置为当前登录用户的名称
})

// 床位选项
const bedOptions = ref([])

// 患者选项
const patientOptions = ref([])

// 获取当前登录用户信息
const getUserInfo = () => {
  const userInfo = store.getters.getUserInfo() || {}
  // 返回用户信息，包括用户名
  return userInfo
}

//获取床位
const getBedList = async () => {
  const res = await http.get('/api/BedController/GetBeds')
  if (res) {
    // 将后端数据格式转换为 el-select 需要的格式
    bedOptions.value = res.map(bed => ({
      value: bed.bedCode,
      label: bed.bedCode
    }))
  } else {
    ElMessage.error('获取床位失败')
  }
}

// 获取患者列表
const getPatientList = async () => {
  try {
    const res = await http.get('/api/DoctorManageController/GetPatients')
    if (res) {
      // 将患者数据转换为下拉框格式
      patientOptions.value = res.map(patient => ({
        value: patient.patientCode,
        label: patient.name,
        ...patient // 保存完整的患者信息以便使用
      }))
    } else {
      ElMessage.error('获取患者列表失败')
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败')
  }
}

// 处理患者选择变化
const handlePatientChange = (patientCode) => {
  // 查找选中的患者完整信息
  const selectedPatient = patientOptions.value.find(p => p.value === patientCode)
  if (selectedPatient) {
    // 设置患者名称和其他可能需要的字段
    form.patientName = selectedPatient.label
    // 如果床位为空，自动填充床位（如果患者有床位信息）
    if (!form.bedCode && selectedPatient.bedCode) {
      form.bedCode = selectedPatient.bedCode
    }
  }
}

// 表单验证规则
const rules = {
  bedCode: [{ required: true, message: '请选择床位', trigger: 'change' }],
  patientCode: [{ required: true, message: '请选择患者', trigger: 'change' }],
  doctorSTime: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  doctorETime: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  doctorContent: [{ required: true, message: '请输入医嘱内容', trigger: 'blur' }]
}

// 加载数据
const loadData = async () => {
  try {
    // 如果有姓名查询条件，则添加到请求参数中
    const params = patientName.value ? { patientName: patientName.value } : {}
    
    const res = await http.get(`/api/DoctorManageController/GetTellList/?patientName=${patientName.value}`)
    if (res && res.status) {
      tableData.value = res.data
    } else {
      ElMessage.error(res?.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 搜索
const searchData = () => {
  loadData()
}

// 重置表单
const resetForm = () => {
  const userInfo = getUserInfo()
  
  form.id = null
  form.bedCode = ''
  form.patientCode = ''
  form.patientName = ''
  form.doctorSTime = ''
  form.doctorETime = ''
  form.doctorContent = ''
  form.doctorCode = userInfo.userName || '默认医生'
  
  // 重置表单验证
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 添加新医嘱
const addNew = () => {
  dialogStatus.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑医嘱
const handleEdit = (row) => {
  dialogStatus.value = 'edit'
  resetForm()
  
  // 填充表单数据
  form.id = row.id
  form.bedCode = row.bedCode
  form.patientCode = row.patientCode || ''
  form.patientName = row.patientName || ''
  form.doctorSTime = formatDate(row.doctorSTime)
  form.doctorETime = formatDate(row.doctorETime)
  form.doctorContent = row.doctorContent
  form.doctorCode = row.doctorCode || getUserInfo().userName || '默认医生'
  
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const isAdd = dialogStatus.value === 'add'
        const userInfo = getUserInfo()
        
        // 构建提交的数据
        const submitData = {
          id: form.id || 0,
          doctorCode: form.doctorCode || userInfo.userName || '默认医生', // 使用当前登录用户的名称
          bedCode: form.bedCode,
          patientCode: form.patientCode || 'string',
          patientName: form.patientName,
          doctorContent: form.doctorContent,
          doctorSTime: form.doctorSTime,
          doctorETime: form.doctorETime,
          isPublisher: 0,
          isDelete: 0
        }
        
        const url = isAdd 
          ? '/api/DoctorManageController/AddTell'
          : '/api/DoctorManageController/UpdTell'
          
        const res = await http.post(url, submitData)
        
        if (res && res.status) {
          ElMessage.success(isAdd ? '添加成功' : '更新成功')
          dialogVisible.value = false
          loadData() // 重新加载数据
        } else {
          ElMessage.error(res?.message || (isAdd ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error(isAdd ? '添加失败:' : '更新失败:', error)
        ElMessage.error(isAdd ? '添加失败' : '更新失败')
      }
    } else {
      return false
    }
  })
}

// 删除医嘱
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除患者"${row.patientName}"的医嘱吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
     row.isDelete=1
      const res = await http.post('/api/DoctorManageController/UpdTell', row)
      if (res && res.status) {
        ElMessage.success('删除成功')
        loadData() // 重新加载数据
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 发布医嘱
const handlePublish = async (row) => {
  try {
    row.isPublisher = 1  // 注意属性名是小写的isPublisher
    // 调用发布API
    const res = await http.post('/api/DoctorManageController/UpdTell', row)
    if (res && res.status) {
      ElMessage.success('发布成功')
      
      // 发送SignalR
      await sendSignalRMessage();
      
      loadData() // 重新加载数据
    } else {
      ElMessage.error(res?.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  } catch (e) {
    return dateString // 如果已经是格式化过的日期字符串，则直接返回
  }
}

// 日期验证器 - 确保结束日期不早于开始日期
const validateEndDate = (rule, value, callback) => {
  if (value && form.doctorSTime && new Date(value) < new Date(form.doctorSTime)) {
    callback(new Error('结束日期不能早于开始日期'))
  } else {
    callback()
  }
}

// 页面加载时获取数据及初始化
onMounted(() => {
  loadData()
  getBedList()
  getPatientList() // 获取患者列表
  initSignalRConnection()
  
  // 初始化doctorCode为当前登录用户的名称
  const userInfo = getUserInfo()
  form.doctorCode = userInfo.userName || '默认医生'
})
</script>

<style scoped>
.tell-manage-container {
  padding: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.search-input {
  width: 200px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.status-published {
  color: #67c23a;
}

.status-unpublished {
  color: #f56c6c;
}

.ml-10 {
  margin-left: 10px;
}

/* 对话框样式 */
:deep(.doctor-dialog .el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
  background-color: #f9f9f9;
  border-radius: 8px 8px 0 0;
}

:deep(.doctor-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.doctor-dialog .el-dialog__body) {
  padding: 30px 20px;
}

:deep(.doctor-dialog .el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #f9f9f9;
  border-radius: 0 0 8px 8px;
}

:deep(.doctor-dialog .el-dialog) {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.doctor-form .el-form-item {
  margin-bottom: 22px;
}

:deep(.doctor-form .el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.doctor-form .el-input__wrapper),
:deep(.doctor-form .el-textarea__wrapper),
:deep(.doctor-form .el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  padding: 1px 15px;
  border-radius: 4px;
  transition: all 0.2s;
}

:deep(.doctor-form .el-input__wrapper:hover),
:deep(.doctor-form .el-textarea__wrapper:hover),
:deep(.doctor-form .el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.doctor-form .el-input__wrapper.is-focus),
:deep(.doctor-form .el-textarea__wrapper.is-focus),
:deep(.doctor-form .el-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.dialog-footer .el-button) {
  min-width: 80px;
  border-radius: 4px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.dialog-footer .el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.dialog-footer .el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>
